package com.zuipin.service.impl;

import java.math.BigDecimal;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zuipin.entity.BalanceRecord;
import com.zuipin.entity.MemberAccount;
import com.zuipin.enums.BalanceType;
import com.zuipin.framework.emuns.ErrorCode;
import com.zuipin.framework.exception.CustomException;
import com.zuipin.mapper.BalanceRecordMapper;
import com.zuipin.service.IBalanceRecordService;
import com.zuipin.service.IMemberAccountService;
import com.zuipin.util.ArithUtil;
import com.zuipin.util.ConstantsUtil;
import com.zuipin.util.DateUtils;
import com.zuipin.util.Pagination;

/**
 * @ClassName: BalanceRecordServiceImpl
 * @author wuyicheng
 * @time 2017年3月27日下午4:00:56
 */
@Service
public class BalanceRecordServiceImpl implements IBalanceRecordService {
	@Resource
	private BalanceRecordMapper		balanceRecordMapper;
	@Resource
	private IMemberAccountService	memberAccountService;
	
	/**
	 * @Title: findById
	 * @author: wuyicheng
	 * @date: 2017年3月27日下午4:42:36
	 * @param id
	 * @return
	 * @throws
	 */
	@Override
	public BalanceRecord findById(Long id) {
		return balanceRecordMapper.findById(id);
	}
	
	/**
	 * @Title: findList
	 * @author: wuyicheng
	 * @date: 2017年3月27日下午4:42:36
	 * @param memberId
	 * @return
	 * @throws
	 */
	@Override
	public List<BalanceRecord> findList(Long memberId) {
		return null;
	}
	
	/**
	 * @Title: insert
	 * @author: wuyicheng
	 * @date: 2017年3月27日下午4:42:36
	 * @param balanceRecord
	 * @throws
	 */
	@Override
	public void insert(BalanceRecord balanceRecord) {
		balanceRecord.setCreateTime(DateUtils.getCurrentDateTime());
		balanceRecord.setUpdateTime(DateUtils.getCurrentDateTime());
		balanceRecord.setDelFlag(ConstantsUtil.DEL_FLAG_NO_0);
		balanceRecordMapper.insert(balanceRecord);
		
	}
	
	/**
	 * @Title: update
	 * @author: wuyicheng
	 * @date: 2017年3月27日下午4:42:36
	 * @param balanceRecord
	 * @throws
	 */
	@Override
	public void update(BalanceRecord balanceRecord) {
		balanceRecord.setUpdateTime(DateUtils.getCurrentDateTime());
		balanceRecordMapper.update(balanceRecord);
		
	}
	
	/**
	 * @Title: deleteById
	 * @author: wuyicheng
	 * @date: 2017年3月27日下午4:42:36
	 * @param id
	 * @throws
	 */
	@Override
	public void deleteById(Long id) {
		balanceRecordMapper.deleteByPrimaryKey(id);
	}
	
	/**
	 * @throws CustomException 
	 * 更新账户余额
	 *
	 * @Title: updateBalance 
	 * @author: wuyicheng
	 * @date: 2017年4月25日下午4:43:05 
	 * @param memberId 会员ID
	 * @param sysId 系统ID
	 * @param createId 创建者ID
	 * @param updateId 修改者ID
	 * @param alterMoney 修改金额
	 * @param balanceType 余额类型
	 * @param remark 备注
	 * @throws
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public void updateBalance(Long memberId, Long sysId, Long createId, Long updateId, BigDecimal alterMoney, BalanceType balanceType, String remark, String describe,
			String oddNumbers, int isBuy) throws CustomException {
		if (alterMoney != null && ArithUtil.compareTo(alterMoney, new BigDecimal(0.00)) != 0) {
			// 积分记录
			BalanceRecord balanceRecord = new BalanceRecord();
			// MemberAccount memberAccount = memberAccountService.findByMemberIdAndSysId(memberId, sysId);
			MemberAccount memberAccount = memberAccountService.findByMemberIdAndSysIdForUpdate(memberId, sysId);
			if (memberAccount != null) {
				/*boolean isBinding = memberAccountService
						.isBindingMobilePhone(memberAccount.getMemberId());
				//账号未绑定手机号，不能操作
				if (!isBinding) {
					throw new CustomException(ErrorCode.DB_EXCEPTION.getCode(),
							"Account not binding mobile phone number, can't operation");
				}*/
				balanceRecord.setBeforeMoney(memberAccount.getTotalAmount());
				// 当前余额
				BigDecimal totalAmount = memberAccount.getTotalAmount();
				// 购物使用充值 减少
				// 累计消费金额 增加
				// if (BalanceType.BUY_USE.equals(balanceType)) {
				// totalAmount = ArithUtil.sub(totalAmount, alterMoney, 2);
				// balanceRecord.setAlterMoney(ArithUtil.mul(totalAmount, new BigDecimal(-1), 2));
				// cumulativeConsume = ArithUtil.add(cumulativeConsume, alterMoney, 2);
				// } else {
				// balanceRecord.setAlterMoney(alterMoney);
				// totalAmount = ArithUtil.add(totalAmount, alterMoney, 2);
				// }
				// 当前累计消费金额
				// BigDecimal cumulativeConsume = memberAccount.getCumulativeConsume();
				// 统计累计消费 购物是减余额
				// if (BalanceType.BUY_USE.equals(balanceType)) {
				// cumulativeConsume = ArithUtil.sub(cumulativeConsume, alterMoney, 2);
				// }
				balanceRecord.setAlterMoney(alterMoney);
				totalAmount = ArithUtil.add(totalAmount, alterMoney, 2);
				// 使用余额大于当前可用余额
				// 0等于，1大于，-1小于
				int totalAmountFlag = ArithUtil.compareTo(totalAmount, new BigDecimal(0));
				int alterMoneyFlag = ArithUtil.compareTo(alterMoney, new BigDecimal(0));
				// 控制积分不能小于零，且是积分减少的操作
				balanceRecord.setAfterMoney(totalAmount);
				if (totalAmountFlag == -1 && alterMoneyFlag == -1) {
					if (BalanceRecord.IS_BUY_YES == isBuy) {
						throw new CustomException(ErrorCode.DB_EXCEPTION.getCode(), "余额不够,请前往充值");
					} else {
						balanceRecord.setAfterMoney(new BigDecimal(0.00));
						balanceRecord
								.setAlterMoney(ArithUtil.mul(new BigDecimal(-1), memberAccount.getTotalAmount() == null ? new BigDecimal(0.00) : memberAccount.getTotalAmount()));
					}
					// throw new CustomException(ErrorCode.DB_EXCEPTION.getCode(), "Use the balance is greater than the current available balance");
				}
				
				balanceRecord.setBalanceType(balanceType);
				balanceRecord.setRemark(remark);
				balanceRecord.setCreateId(createId);
				balanceRecord.setUpdateId(updateId);
				balanceRecord.setMemberId(memberId);
				balanceRecord.setSysId(sysId);
				balanceRecord.setDescribes(describe);
				balanceRecord.setOddNumbers(oddNumbers);
				insert(balanceRecord);
				// 修改账户余额
				MemberAccount tempMemberAccount = new MemberAccount();
				tempMemberAccount.setId(memberAccount.getId());
				tempMemberAccount.setTotalAmount(totalAmount);
				// tempMemberAccount.setCumulativeConsume(cumulativeConsume);
				memberAccountService.updateAmount(memberAccount.getId(), balanceRecord.getAlterMoney());
				
			} else {
				throw new CustomException(ErrorCode.DB_EXCEPTION.getCode(), "memberAccount is not exist");
			}
		}
	}
	
	/** 
	 *
	 * @Title: findListByPage 
	 * @author: wuyicheng
	 * @date: 2017年4月25日下午3:51:17 
	 * @param balanceRecord
	 * @param page
	 * @return
	 * @throws 
	 */
	@Override
	public List<BalanceRecord> findListByPage(BalanceRecord balanceRecord, Pagination page) {
		return balanceRecordMapper.findListByPage(balanceRecord, page);
	}
	
	@Override
	public BigDecimal getCurrentBalance(Long memberId, Long sysId) {
		// TODO Auto-generated method stub
		return balanceRecordMapper.getCurrentBalance(memberId, sysId);
	}
	
	@Override
	public boolean queryPayStatusByOddNumbers(Long sysId, String oddNumbers) {
		List<BalanceRecord> list = balanceRecordMapper.queryPayStatusByOddNumbers(sysId, oddNumbers, BalanceType.PAY);
		if (list != null && list.size() > 0) {
			return true;
		}
		return false;
	}
	
}
